define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    console.log('purchase_inbound.js文件已加载');

    var Controller = {
        index: function () {
            console.log('purchase_inbound index方法被调用');
            // 初始化表格参数
            Table.api.init({
                extend: {
                    index_url: 'scanwork/purchase_inbound/index' + location.search,
                    add_url: 'scanwork/purchase_inbound/add',
                    edit_url: 'scanwork/purchase_inbound/edit',
                    del_url: 'scanwork/purchase_inbound/del',
                    multi_url: 'scanwork/purchase_inbound/multi',
                    import_url: 'scanwork/purchase_inbound/import',
                    table: 'scanwork_purchase_inbound',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'inbound_no', title: '入库单号', operate: 'LIKE'},
                        {field: 'supplier_id', title: '供应商', operate: 'LIKE', formatter: function(value, row, index) {
                            return row.supplier ? row.supplier.name : '';
                        }},
                        {field: 'inbound_date', title: '入库日期', operate:'BETWEEN', sortable: true, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'total_amount', title: '总金额', operate:'BETWEEN', sortable: true, formatter: function(value, row, index) {
                            var amount = parseFloat(value) || 0;
                            return '¥' + amount.toFixed(2);
                        }},
                        {field: 'status_text', title: '状态', formatter: function(value, row, index) {
                            var status = String(row.status);
                            var statusClass = '';
                            var statusText = '';
                            
                            switch(status) {
                                case '1': statusClass = 'label-warning'; statusText = '待入库'; break;
                                case '2': statusClass = 'label-success'; statusText = '已入库'; break;
                                case '3': statusClass = 'label-default'; statusText = '已取消'; break;
                                default: statusClass = 'label-default'; statusText = '未知'; break;
                            }
                            
                            return '<span class="label ' + statusClass + '">' + statusText + '</span>';
                        }},
                        {field: 'inbound_user.username', title: '操作员'},
                        {field: 'remark', title: '备注', operate: 'LIKE'},
                        {field: 'createtime', title: '创建时间', operate:'BETWEEN', sortable: true, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: function(value, row, index) {
                            var that = this;
                            var table = that.table;
                            var options = table ? table.bootstrapTable('getOptions') : {};
                            
                            // 使用标准的operate格式化器生成编辑删除按钮
                            var buttons = Table.api.formatter.operate.call(this, value, row, index);
                            
                            // 查看明细按钮
                            buttons += ' <a class="btn btn-info btn-xs btn-view-items" data-id="' + row.id + '" title="查看明细"><i class="fa fa-list"></i></a>';
                            
                            // 确认入库按钮（只有待入库状态才显示）
                            if (row.status == 1) {
                                buttons += ' <a class="btn btn-success btn-xs btn-confirm-inbound" data-id="' + row.id + '" title="确认入库"><i class="fa fa-check"></i></a>';
                            }
                            
                            return buttons;
                        }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 从采购申请生成入库单按钮事件
            $(document).on('click', '.btn-generate-from-request', function() {
                Fast.api.open('scanwork/purchase_inbound/generateFromRequest', '从采购申请生成入库单', {
                    callback: function(data) {
                        table.bootstrapTable('refresh');
                    }
                });
            });
            
            // 查看明细按钮事件
            $(document).on('click', '.btn-view-items', function() {
                var id = $(this).data('id');
                Fast.api.open('scanwork/purchase_inbound/viewItems?ids=' + id, '查看入库明细', {
                    callback: function(data) {
                        table.bootstrapTable('refresh');
                    }
                });
            });
            
            // 确认入库按钮事件
            $(document).on('click', '.btn-confirm-inbound', function() {
                var id = $(this).data('id');
                Layer.confirm('确定要确认这个入库单吗？确认后将更新物料库存。', function(index) {
                    // 使用jQuery AJAX避免FastAdmin的自动加载层
                    $.ajax({
                        url: Fast.api.fixurl('scanwork/purchase_inbound/confirmInbound'),
                        type: 'POST',
                        data: {ids: id},
                        dataType: 'json',
                        success: function(data) {
                            // 先关闭确认对话框
                            Layer.close(index);
                            
                            if (data.code == 1) {
                                Toastr.success(data.msg || '入库确认成功');
                                // 延迟刷新表格，避免加载层问题
                                setTimeout(function() {
                                    table.bootstrapTable('refresh');
                                }, 300);
                            } else {
                                Toastr.error(data.msg || '确认失败');
                            }
                        },
                        error: function(xhr, status, error) {
                            Layer.close(index);
                            Toastr.error('确认失败：' + error);
                        }
                    });
                });
            });
        },
        
        add: function () {
            Controller.api.bindevent();
        },
        
        edit: function () {
            Controller.api.bindevent();
        },
        
        generateFromRequest: function () {
            console.log('generateFromRequest方法被调用');
            console.log('当前页面URL:', window.location.href);
            console.log('当前页面标题:', document.title);
            // 初始化表格参数
            Table.api.init({
                extend: {
                    index_url: 'scanwork/purchase_inbound/generateFromRequest' + location.search,
                    table: 'scanwork_purchase_request',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'scanwork/purchase_request/index' + location.search,
                pk: 'id',
                sortName: 'id',
                onLoadError: function(status, xhr) {
                    console.log('表格加载错误:', status, xhr);
                },
                onLoadSuccess: function(data) {
                    console.log('表格加载成功:', data);
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'material.name', title: '物料名称'},
                        {field: 'material.code', title: '物料编码'},
                        {field: 'supplier.name', title: '供应商'},
                        {field: 'request_quantity', title: '申请数量', formatter: function(value, row, index) {
                            return value + ' ' + (row.material ? row.material.unit : '');
                        }},
                        {field: 'priority_text', title: '优先级', formatter: function(value, row, index) {
                            var priority = String(row.priority);
                            var priorityClass = '';
                            var priorityText = '';
                            
                            switch(priority) {
                                case '1': priorityClass = 'label-default'; priorityText = '低'; break;
                                case '2': priorityClass = 'label-info'; priorityText = '中'; break;
                                case '3': priorityClass = 'label-warning'; priorityText = '高'; break;
                                case '4': priorityClass = 'label-danger'; priorityText = '紧急'; break;
                                default: priorityClass = 'label-default'; priorityText = '中'; break;
                            }
                            
                            return '<span class="label ' + priorityClass + '">' + priorityText + '</span>';
                        }},
                        {field: 'status_text', title: '状态', formatter: function(value, row, index) {
                            var status = String(row.status);
                            var statusClass = '';
                            var statusText = '';
                            
                            switch(status) {
                                case '1': statusClass = 'label-warning'; statusText = '待审核'; break;
                                case '2': statusClass = 'label-info'; statusText = '已审核'; break;
                                case '3': statusClass = 'label-success'; statusText = '已采购'; break;
                                case '4': statusClass = 'label-default'; statusText = '已取消'; break;
                                default: statusClass = 'label-default'; statusText = '未知'; break;
                            }
                            
                            return '<span class="label ' + statusClass + '">' + statusText + '</span>';
                        }},
                        {field: 'request_time', title: '申请时间', formatter: Table.api.formatter.datetime}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 生成入库单按钮事件
            console.log('正在绑定.btn-generate-inbound按钮事件');
            
            // 检查按钮是否存在
            setTimeout(function() {
                var button = $('.btn-generate-inbound');
                console.log('找到按钮数量:', button.length);
                console.log('按钮元素:', button);
                if (button.length > 0) {
                    console.log('按钮HTML:', button[0].outerHTML);
                }
            }, 1000);
            
            $(document).on('click', '.btn-generate-inbound', function() {
                console.log('生成入库单按钮被点击');
                var ids = Table.api.selectedids(table);
                console.log('选中的ID:', ids);
                if (ids.length === 0) {
                    Toastr.warning('请选择要生成入库单的采购申请');
                    return;
                }
                
                // 检查选中的申请是否都是已审核状态
                var validIds = [];
                console.log('检查选中记录的状态...');
                table.bootstrapTable('getData').forEach(function(row) {
                    console.log('记录ID:', row.id, '状态:', row.status, '是否选中:', ids.indexOf(row.id) !== -1);
                    if (ids.indexOf(row.id) !== -1 && row.status == 2) {
                        validIds.push(row.id);
                    }
                });
                
                console.log('有效ID列表:', validIds);
                if (validIds.length === 0) {
                    Toastr.warning('选中的采购申请中没有已审核状态的申请');
                    return;
                }
                
                if (validIds.length !== ids.length) {
                    Toastr.warning('部分选中的申请不是已审核状态，将只处理已审核的申请');
                }
                
                console.log('准备显示确认对话框，有效ID:', validIds);
                Layer.confirm('确定要为选中的采购申请生成入库单吗？', function(index) {
                    console.log('用户确认，开始发送AJAX请求');
                    
                    // 使用jQuery AJAX避免FastAdmin的自动加载层
                    $.ajax({
                        url: Fast.api.fixurl('scanwork/purchase_inbound/generateFromRequest'),
                        type: 'POST',
                        data: {request_ids: validIds.join(',')},
                        dataType: 'json',
                        success: function(data, ret) {
                            console.log('AJAX请求成功:', data, ret);
                            // 先关闭确认对话框
                            Layer.close(index);
                            
                            if (data.code == 1) {
                                Toastr.success(data.msg || '入库单生成成功');
                                // 延迟刷新采购申请列表，避免加载层问题
                                setTimeout(function() {
                                    table.bootstrapTable('refresh');
                                }, 300);
                            } else {
                                Toastr.error(data.msg || '生成失败');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.log('AJAX请求失败:', xhr, status, error);
                            Toastr.error('生成失败：' + error);
                        }
                    });
                });
            });
        },
        
        viewItems: function () {
            // 查看入库明细页面
            var table = $("#table");
            
            // 初始化表格
            table.bootstrapTable({
                url: 'scanwork/purchase_inbound/viewItems' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {field: 'id', title: __('Id')},
                        {field: 'material.name', title: '物料名称'},
                        {field: 'material.code', title: '物料编码'},
                        {field: 'request_quantity', title: '申请数量', formatter: function(value, row, index) {
                            return value + ' ' + (row.material ? row.material.unit : '');
                        }},
                        {field: 'actual_quantity', title: '实际数量', formatter: function(value, row, index) {
                            return value + ' ' + (row.material ? row.material.unit : '');
                        }},
                        {field: 'unit_price', title: '单价', formatter: function(value, row, index) {
                            return '¥' + parseFloat(value).toFixed(2);
                        }},
                        {field: 'total_amount', title: '总金额', formatter: function(value, row, index) {
                            return '¥' + parseFloat(value).toFixed(2);
                        }},
                        {field: 'batch_no', title: '批次号'},
                        {field: 'quality_status_text', title: '质检状态'},
                        {field: 'location', title: '存放位置'},
                        {field: 'remark', title: '备注'}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        
        test: function () {
            console.log('测试方法被调用');
            $('.btn-test').click(function() {
                console.log('测试按钮被点击');
                alert('测试按钮工作正常！');
            });
        },
        
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    console.log('purchase_inbound.js文件加载完成，Controller对象:', Controller);
    
    // 测试方法调用
    setTimeout(function() {
        console.log('尝试手动调用generateFromRequest方法');
        if (typeof Controller.generateFromRequest === 'function') {
            console.log('generateFromRequest方法存在，正在调用...');
            Controller.generateFromRequest();
        } else {
            console.log('generateFromRequest方法不存在');
        }
    }, 2000);
    
    return Controller;
});